package com.StarStudio.Service.Impl;

import cn.hutool.core.util.IdUtil;
import com.StarStudio.DAO.CouponsDAO;
import com.StarStudio.DAO.PanicBuyingCouponsDAO;
import com.StarStudio.DAO.PanicBuyingOrdersDAO;
import com.ruoyi.common.core.Entity.Coupons;
import com.ruoyi.common.core.Entity.Goods;
import com.ruoyi.common.core.Entity.PanicBuyingCoupons;
import com.StarStudio.Service.PanicBuyingCouponsService;
import com.ruoyi.common.core.Entity.PanicBuyingGoods;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PanicBuyingCouponsServiceImpl implements PanicBuyingCouponsService {

    @Autowired
    PanicBuyingCouponsDAO panicBuyingCouponsDAO;

    @Autowired
    CouponsDAO couponsDAO;

    @Autowired
    RedisService redisService;

    @Autowired
    PanicBuyingOrdersDAO panicBuyingOrdersDAO;

    public List<PanicBuyingCoupons> findPanicBuyingCouponsList(PanicBuyingCoupons panicBuyingCoupons) {
        List<PanicBuyingCoupons> panicBuyingCouponsList = panicBuyingCouponsDAO.findPanicBuyingCouponsList(panicBuyingCoupons);
        if (panicBuyingCouponsList != null && panicBuyingCouponsList.size() > 0){
            for (PanicBuyingCoupons buyingCoupons : panicBuyingCouponsList) {
                Coupons coupons = couponsDAO.findByCoupon_id(buyingCoupons.getCoupons_id());
                Map<String,Object> param = new HashMap<>();
                param.put("couponsName",coupons.getCoupon_name());
                buyingCoupons.setParams(param);
            }
        }
        return panicBuyingCouponsList;
    }

    @Override
    public long findTotalRecord() {
        return panicBuyingCouponsDAO.findTotalRecord();
    }

    @Override
    public PanicBuyingCoupons findByCoupons_id(Long coupons_id) {
        return panicBuyingCouponsDAO.findByCoupons_id(coupons_id);
    }

    @Override
    public List<PanicBuyingCoupons> PanicBuyingCouponsList() {
        return panicBuyingCouponsDAO.PanicBuyingCouponsList();
    }

    @Override
    public int updatePanicBuyingCoupons(PanicBuyingCoupons panicBuyingCoupons) {
        int new_pb_coupons_stock = panicBuyingCoupons.getPanic_buying_coupons_stock();
        int old_pb_coupons_stock = panicBuyingCouponsDAO.findPanic_buying_coupons_stockByPanic_buying_coupons_id(panicBuyingCoupons.getPanic_buying_coupons_id());
        if (new_pb_coupons_stock != old_pb_coupons_stock){
            Coupons byCoupon_id = couponsDAO.findByCoupon_id(panicBuyingCoupons.getCoupons_id());
            int totalStock = byCoupon_id.getStock() + old_pb_coupons_stock;
            if (new_pb_coupons_stock > old_pb_coupons_stock){ /* 抢购优惠券库存增加 */
                if (new_pb_coupons_stock <= totalStock){
                    byCoupon_id.setStock(totalStock - new_pb_coupons_stock);
                }else {
                    throw new RuntimeException("优惠券库存不足！");
                }
            } else { /* 抢购优惠券库存减少 */
                if (new_pb_coupons_stock >= 0){
                    byCoupon_id.setStock(totalStock - new_pb_coupons_stock);
                }else {
                    throw new RuntimeException("库存不能小于零！");
                }
            }
            couponsDAO.updateCoupons(byCoupon_id);
        }
        return panicBuyingCouponsDAO.updatePanicBuyingCoupons(panicBuyingCoupons);
    }

    @Override
    public void AddPanicBuyingCoupons(PanicBuyingCoupons panicBuyingCoupons) {
        Coupons byCoupon_id = couponsDAO.findByCoupon_id(panicBuyingCoupons.getCoupons_id());
        if (byCoupon_id.getStock() >= panicBuyingCoupons.getPanic_buying_coupons_stock()){
            byCoupon_id.setStock(byCoupon_id.getStock() - panicBuyingCoupons.getPanic_buying_coupons_stock());
            couponsDAO.updateCoupons(byCoupon_id);
            panicBuyingCoupons.setDel_flag(false);
            panicBuyingCoupons.setPanic_buying_coupons_id(IdUtil.getSnowflakeNextId()); //使用雪花ID
            panicBuyingCouponsDAO.AddPanicBuyingCoupons(panicBuyingCoupons);
        }else {
            throw new RuntimeException("优惠券库存不足！");
        }
    }

    @Override
    public void DeletePanicBuyingCoupons(Long panic_buying_coupons_id) {
        //删除抢购优惠券时，把库存归还到对应的普通优惠券库存中
        int pbc_stock = panicBuyingCouponsDAO.findPanic_buying_coupons_stockByPanic_buying_coupons_id(panic_buying_coupons_id);
        long couponsId = panicBuyingCouponsDAO.findCouponsIdByPBCId(panic_buying_coupons_id);
        int OldStock = couponsDAO.findStockByCouponsId(couponsId);
        couponsDAO.updateStockById(couponsId,OldStock + pbc_stock);
        //逻辑删除抢购优惠券
        panicBuyingCouponsDAO.DeletePanicBuyingCoupons(panic_buying_coupons_id);
    }

    @Override
    public List<Long> getCouponsIdListFromPanicBuyingCoupons() {
        return panicBuyingCouponsDAO.getCouponsIdListFromPanicBuyingCoupons();
    }

    @Override
    public Long findCouponsIdByRecordId(Long panicBuyingCouponsId) {
        return panicBuyingCouponsDAO.findCouponsIdByPBCId(panicBuyingCouponsId);
    }

    /**
     * 每 30秒更新抢购优惠券状态
     */
    @Scheduled(cron = "*/30 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void AutoUpdatePanicBuyingStatus(){
        List<PanicBuyingCoupons> panicBuyingCouponsList = panicBuyingCouponsDAO.PanicBuyingCouponsList();
        if (!CollectionUtils.isEmpty(panicBuyingCouponsList)){
            for (PanicBuyingCoupons panicBuyingCoupons : panicBuyingCouponsList) {
                int status;
                if (new Timestamp(new Date().getTime()).before(panicBuyingCoupons.getPanic_buying_start_time())){
                    status = 0;
                }else if (new Timestamp(new Date().getTime()).after(panicBuyingCoupons.getPanic_buying_end_time())){
                    status = 2;
                    //获取对应普通优惠券,将抢购优惠券库存归还到对应的普通优惠券库存
                    Coupons coupons = couponsDAO.findByCoupon_id(panicBuyingCoupons.getCoupons_id());
                    coupons.setStock(coupons.getStock() + panicBuyingCoupons.getPanic_buying_coupons_stock());
                    couponsDAO.updateCoupons(coupons);
                    //将抢购商品库存归 0
                    PanicBuyingCoupons update = new PanicBuyingCoupons();
                    BeanUtils.copyProperties(panicBuyingCoupons,update);
                    update.setPanic_buying_coupons_stock(0);
                    panicBuyingCouponsDAO.updatePanicBuyingCoupons(update);
                }else {
                    status = 1;
                }
                panicBuyingCouponsDAO.updatePanicBuyingCouponsStatus(panicBuyingCoupons.getPanic_buying_coupons_id(), status);
            }
        }
    }

    /**
     * 每天00:00:00删除Redis中的抢购优惠券多余数据
     * @Author ChengLee
     * @Date 2023/05/22
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void ClearRedisRedundantData(){
        List<PanicBuyingCoupons> panicBuyingCouponsList = panicBuyingCouponsDAO.PanicBuyingEndStatusCouponsList();
        if (!CollectionUtils.isEmpty(panicBuyingCouponsList)){
            for (PanicBuyingCoupons panicBuyingCoupons : panicBuyingCouponsList) {
                //如果抢购已结束，删除Redis中该优惠券相关数据  1.抢购优惠券数据  2.抢购订单数据
                //panic_buying_coupons:1652163351053926400
                redisService.deleteObject("panic_buying_coupons:" + panicBuyingCoupons.getCoupons_id());
                //panic_buying_coupons_order:3051489:1652163351053926400
                //查询该抢购优惠券对应订单的用户ID
                List<Long> userIdList = panicBuyingOrdersDAO.findUserIdListByCouponsId(panicBuyingCoupons.getCoupons_id());
                if (!CollectionUtils.isEmpty(userIdList)){
                    for (Long userId : userIdList) {
                        redisService.deleteObject("panic_buying_coupons_order:" + userId + ":" + panicBuyingCoupons.getCoupons_id());
                    }
                }
            }
        }
    }
}
